package com.nlp.trie.experiment3;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

/**
 * 词条表
 * @author ygsong.abcft
 *
 */
public class TermList {
	
	/**
	 * 文档列表
	 */
	private final List<String> document = new ArrayList<>();
	
	/**
	 * 词条集合
	 */
	private final Map<Term, Term> set = new TreeMap<Term, Term>();
	
	/**
	 * 获取Term词条列表
	 * @return
	 */
	public List<Term> getList(){
		return new ArrayList<Term>(set.keySet());
	}
	
	/**
	 * 获得文档集合
	 * @return
	 */
	public List<String> getDocument(){
		return new ArrayList<String>(document);
	}
	
	/**
	 * 根据word获得term
	 */
	public Term getTerm(String word) {
		Term term = new Term();
		term.setWord(word);
		return set.getOrDefault(term, null);
	}
	
	/**
	 * 根据content构造TermList
	 * @param content
	 */
	public TermList(String content) {
		String[] msg = content
                .replaceAll("\n.{0,20}/m", "")
                .replaceAll(" .{1,8}/m", "")
                .replaceAll("\\[", "").replaceAll("]", "")
                .replaceAll("/[a-z|A-Z]{1,3}", "").split("\n");
		msg[0] = msg[0].substring(msg[0].indexOf(' ')+1);
		for (int i = 0; i < msg.length; i++) {
			String[] words = msg[i].split("\\s");
			for (String word : words) {
				if (!"".equals(word.trim())) {
					addTerm(word, i);
				}
			}
			msg[i] = msg[i].replaceAll(" ", "").trim();
		}
		document.addAll(Arrays.asList(msg));
	}

	/**
	 * 添加一条词条
	 * @param word
	 * @param docId
	 */
	private void addTerm(String word, int docId) {
		Term term = new Term();
		term.setWord(word);
		if (set.containsKey(term)) {
			term = set.get(term);
		}
		set.put(term.add(docId), term);
	}
	
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		for (Term term : getList()) {
			sb.append(term.getWord() + "\t" + term.getFreq() + "\t" + term.getNdoc());
			for (Entry<Integer, Integer> entry : term.getMap().entrySet()) {
				sb.append("\t").append(entry.getKey()).append("\t").append(entry.getValue());
			}
			sb.append("\r\n");
		}
		return sb.toString();
	}
	
	public String indexOfDocment(int index) {
		return document.get(index);
	}
}
